package com.adingxiong.cft.util;

import com.adingxiong.cft.errors.Assert;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName UnicodeUtil
 * @Description  编码格式工具类
 * @Author xiongchao
 * @Date 2020/11/9 15:39
 **/
@Slf4j
public class UnicodeUtil {

    public static String toUtf8String(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    log.error("将文件名中的汉字转为UTF8编码的串时错误，输入的字符串为：{}", s, ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k += 256;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 根据不同浏览器将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
     *
     * @param s
     *            原文件名
     * @return 重新编码后的文件名
     */
    public static String toUtf8String(HttpServletRequest request, String s) {
        String agent = request.getHeader("User-Agent");
        if(agent == null){
            Assert.fail("获取浏览器代理信息异常");
        }
        try {
            boolean isFireFox = agent.toLowerCase().indexOf("firefox") != -1;
            if (isFireFox) {
                s = new String(s.getBytes("UTF-8"), "ISO8859-1");
            } else {
                s = toUtf8String(s);
                if (agent.indexOf("MSIE") != -1 && s.length() > 150) {
                    // see http://support.microsoft.com/default.aspx?kbid=816868
                    // 根据request的locale 得出可能的编码
                    s = new String(s.getBytes("UTF-8"), "ISO8859-1");
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.error("将文件名中的汉字转为UTF8编码的串时错误，输入的字符串为：{}", s, e);
        }
        return s;
    }
}
